package com.exject.android.socialphonebook.view;

import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.provider.Contacts;
import android.provider.Contacts.PeopleColumns;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CursorAdapter;
import android.widget.Filterable;
import android.widget.TextView;

import com.exject.android.socialphonebook.R;

public class ContactListAdapter extends CursorAdapter implements Filterable {
	private final ContentResolver mContent;

	public ContactListAdapter(final Context context, final Cursor c) {
		super(context, c);
		this.mContent = context.getContentResolver();
	}

	@Override
	public void bindView(final View view, final Context context,
			final Cursor cursor) {
		TextView name = (TextView) view
				.findViewById(R.id.contactListContactName);
		name.setText(cursor.getString(cursor
				.getColumnIndex(PeopleColumns.DISPLAY_NAME)));
	}

	@Override
	public String convertToString(final Cursor cursor) {
		return cursor.getString(cursor
				.getColumnIndex(PeopleColumns.DISPLAY_NAME));
	}

	@Override
	public View newView(final Context context, final Cursor cursor,
			final ViewGroup parent) {
		final LayoutInflater inflater = LayoutInflater.from(context);
		final View resultView = inflater.inflate(R.layout.contact_list_entry,
				null);

		final TextView contactListContactName = (TextView) resultView
				.findViewById(R.id.contactListContactName);
		contactListContactName.setText(""
				+ cursor.getString(cursor
						.getColumnIndex(PeopleColumns.DISPLAY_NAME)));
		return resultView;
	}

	public static String getNameFromElement(View view) {
		TextView name = (TextView) view
				.findViewById(R.id.contactListContactName);
		return name.getText().toString();
	}

	@Override
	public Cursor runQueryOnBackgroundThread(final CharSequence constraint) {
		if (this.getFilterQueryProvider() != null) {
			return this.getFilterQueryProvider().runQuery(constraint);
		}

		StringBuilder buffer = null;
		String[] args = null;
		if (constraint != null) {
			buffer = new StringBuilder();
			buffer.append("UPPER(");
			buffer.append(PeopleColumns.NAME);
			buffer.append(") GLOB ?");
			args = new String[] { constraint.toString().toUpperCase() + "*" };
		}

		// TODO: PROJECTION ?!?
		return this.mContent.query(Contacts.People.CONTENT_URI, null,
				buffer == null ? null : buffer.toString(), args,
				Contacts.People.DEFAULT_SORT_ORDER);
	}
}
